package org.monkey.common.generator.util;

import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import cn.hutool.json.JSONUtil;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.monkey.common.constant.entity.ErrorResultEnum;
import org.monkey.common.constant.exception.BaseException;


@Slf4j
public class FormatUtil {

  private static  final TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig());



  public static void format(String templateStr, String filePath, Map<String, Object> map) {
    log.info("generator file:{}",filePath);
    if (StringUtils.isNotBlank(templateStr)) {
      Template template = engine.getTemplate(templateStr);
      template.render(map, new File(filePath));
    } else {
      try {
        FileWriter writer = new FileWriter(filePath);
        writer.append("file template not found\r\n");
        writer.append("param:" + JSONUtil.toJsonStr(map));
        writer.close();
      } catch (IOException e) {
        log.error("文件生成失败：", e);
        throw new BaseException(ErrorResultEnum.SYSTEM_ERROR);
      }
    }

  }
}
